<template>
  <div class="available-orders-container">
    <el-card class="orders-card">
      <template #header>
        <div class="card-header">
          <h2>可接订单</h2>
          <el-button type="primary" @click="refreshOrderList" :loading="loading">
            <el-icon><Refresh /></el-icon>刷新列表
          </el-button>
        </div>
      </template>
      
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单号、寄件人、收件人"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="sortBy" placeholder="排序方式" class="filter-select" @change="refreshOrderList">
          <el-option label="时间优先" value="time" />
          <el-option label="费用优先" value="fee" />
          <el-option label="距离优先" value="distance" />
        </el-select>
        
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      
      <!-- 订单列表 -->
      <div class="order-list" v-if="orderList.length > 0">
        <div class="order-item" v-for="order in orderList" :key="order.deliveryOrderId">
          <div class="order-header">
            <div class="order-number">
              <strong>{{ order.orderNumber }}</strong>
              <el-tag type="danger" size="small">待揽收</el-tag>
            </div>
            <div class="order-fee">
              <span class="fee-amount">¥{{ order.totalFee }}</span>
            </div>
          </div>
          
          <div class="order-content">
            <div class="address-info">
              <div class="sender-info">
                <div class="info-label">
                  <el-icon><LocationFilled /></el-icon>
                  寄件
                </div>
                <div class="info-content">
                  <div class="contact">{{ order.senderName }} {{ order.senderPhone }}</div>
                  <div class="address">{{ order.senderAddress }}</div>
                </div>
              </div>
              
              <div class="receiver-info">
                <div class="info-label">
                  <el-icon><Location /></el-icon>
                  收件
                </div>
                <div class="info-content">
                  <div class="contact">{{ order.receiverName }} {{ order.receiverPhone }}</div>
                  <div class="address">{{ order.receiverAddress }}</div>
                </div>
              </div>
            </div>
            
            <div class="item-info">
              <div class="item-detail">
                <span>物品类型：{{ getItemTypeText(order.itemType) }}</span>
                <span>重量：{{ order.itemWeight }}kg</span>
                <span>体积：{{ order.itemVolume }}m³</span>
              </div>
              <div class="fee-detail">
                <span>基础费用：¥{{ order.baseFee }}</span>
                <span>重量费用：¥{{ order.weightFee }}</span>
                <span>服务费用：¥{{ order.serviceFee }}</span>
                <span v-if="order.insuranceFee > 0">保险费用：¥{{ order.insuranceFee }}</span>
              </div>
            </div>
            
            <div class="order-remark" v-if="order.remark">
              <div class="remark-label">备注：</div>
              <div class="remark-content">{{ order.remark }}</div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-time">
              下单时间：{{ formatDateTime(order.createdAt) }}
            </div>
            <div class="order-actions">
              <el-button size="small" @click="viewOrderDetail(order)">查看详情</el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleAcceptOrder(order)"
                :loading="acceptingOrderId === order.deliveryOrderId"
              >
                接单
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div class="empty-placeholder" v-if="orderList.length === 0 && !loading">
        <el-empty description="暂无可接订单"></el-empty>
      </div>
      
      <!-- 加载状态 -->
      <div class="loading" v-if="loading">
        <el-skeleton :rows="3" animated />
      </div>
    </el-card>
    
    <!-- 接单确认对话框 -->
    <el-dialog
      v-model="acceptDialogVisible"
      title="接单确认"
      width="500px"
      @close="resetAcceptForm"
    >
      <div class="accept-dialog-content">
        <div class="order-summary">
          <h4>订单信息</h4>
          <p>订单号：{{ selectedOrder?.orderNumber }}</p>
          <p>寄件人：{{ selectedOrder?.senderName }}</p>
          <p>收件人：{{ selectedOrder?.receiverName }}</p>
          <p>配送费用：¥{{ selectedOrder?.totalFee }}</p>
        </div>
        
        <el-form :model="acceptForm" label-width="80px">
          <el-form-item label="接单备注">
            <el-input
              v-model="acceptForm.remark"
              type="textarea"
              placeholder="请输入接单备注（可选）"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="acceptDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAcceptOrder" :loading="accepting">
            确认接单
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 订单详情模态框 -->
    <OrderDetailModal
      v-model:visible="orderDetailVisible"
      :order-id="selectedOrderId"
      :show-start-delivery-btn="true"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search, Refresh, LocationFilled, Location } from '@element-plus/icons-vue'
import { courierApi, type AvailableOrder } from '@/api/courier'
import { ElMessage, ElMessageBox } from 'element-plus'
import OrderDetailModal from '@/views/myAssignments/components/OrderDetailModal.vue'

const searchQuery = ref('')
const sortBy = ref('time')
const orderList = ref<AvailableOrder[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 接单相关
const acceptDialogVisible = ref(false)
const selectedOrder = ref<AvailableOrder | null>(null)
const acceptForm = ref({
  remark: ''
})
const accepting = ref(false)
const acceptingOrderId = ref<number | null>(null)

// 订单详情相关
const orderDetailVisible = ref(false)
const selectedOrderId = ref<number | null>(null)

// 获取可接订单列表
const getAvailableOrders = async () => {
  loading.value = true
  try {
    console.log('开始获取可接订单列表')
    const response = await courierApi.getAvailableOrders(currentPage.value, pageSize.value)
    console.log('可接订单响应:', response)
    
    if (response.code === 200) {
      orderList.value = response.data.list || []
      total.value = response.data.total || 0
      console.log('获取到订单数量:', orderList.value.length)
    } else {
      console.error('获取可接订单失败，响应码:', response.code)
      ElMessage.error(response.message || '获取可接订单失败')
      orderList.value = []
      total.value = 0
    }
  } catch (error: any) {
    console.error('获取可接订单异常:', error)
    console.error('错误详情:', {
      message: error.message,
      code: error.code,
      response: error.response
    })
    ElMessage.error('获取可接订单失败')
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 测试API连接
const testApiConnection = async () => {
  console.log('测试API连接...')
  try {
    // 先测试获取订单列表接口是否正常
    const response = await courierApi.getAvailableOrders(1, 1)
    console.log('API连接测试成功:', response)
    return true
  } catch (error) {
    console.error('API连接测试失败:', error)
    ElMessage.warning('API连接异常，请检查网络或联系管理员')
    return false
  }
}

// 刷新订单列表
const refreshOrderList = () => {
  getAvailableOrders()
}

// 处理搜索
const handleSearch = () => {
  // 这里可以根据需要实现搜索逻辑
  // 目前先简单刷新列表
  currentPage.value = 1
  getAvailableOrders()
}

// 重置搜索
const handleReset = () => {
  searchQuery.value = ''
  sortBy.value = 'time'
  currentPage.value = 1
  getAvailableOrders()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getAvailableOrders()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getAvailableOrders()
}

// 查看订单详情
const viewOrderDetail = (order: AvailableOrder) => {
  selectedOrderId.value = order.deliveryOrderId
  orderDetailVisible.value = true
}

// 处理接单
const handleAcceptOrder = (order: AvailableOrder) => {
  selectedOrder.value = order
  acceptDialogVisible.value = true
}

// 确认接单
const confirmAcceptOrder = async () => {
  if (!selectedOrder.value) return
  
  accepting.value = true
  acceptingOrderId.value = selectedOrder.value.deliveryOrderId
  
  try {
    console.log('开始接单，订单ID:', selectedOrder.value.deliveryOrderId)
    console.log('接单备注:', acceptForm.value.remark)
    
    const response = await courierApi.acceptOrder({
      orderId: selectedOrder.value.deliveryOrderId,
      remark: acceptForm.value.remark
    })
    
    console.log('接单响应:', response)
    
    if (response.code === 200) {
      ElMessage.success('接单成功！')
      acceptDialogVisible.value = false
      // 刷新列表，移除已接的订单
      getAvailableOrders()
    } else {
      console.error('接单失败，响应码:', response.code, '错误信息:', response.message)
      ElMessage.error(response.message || '接单失败')
    }
  } catch (error: any) {
    console.error('接单请求异常:', error)
    console.error('错误详情:', {
      message: error.message,
      code: error.code,
      response: error.response,
      stack: error.stack
    })
    
    if (error.code === 400) {
      ElMessage.error(error.message || '订单状态不正确，无法接单')
    } else if (error.code === 404) {
      ElMessage.error('订单不存在')
    } else if (error.code === 401) {
      ElMessage.error('用户未登录，请先登录')
    } else if (error.message) {
      ElMessage.error(`接单失败: ${error.message}`)
    } else {
      ElMessage.error('接单失败，请稍后重试')
    }
  } finally {
    accepting.value = false
    acceptingOrderId.value = null
  }
}

// 重置接单表单
const resetAcceptForm = () => {
  acceptForm.value.remark = ''
  selectedOrder.value = null
}

// 获取物品类型文本
const getItemTypeText = (itemType: string) => {
  const typeMap: { [key: string]: string } = {
    'electronics': '电子产品',
    'clothes': '服装',
    'food': '食品',
    'books': '书籍',
    'documents': '文件',
    'fragile': '易碎品',
    'other': '其他'
  }
  return typeMap[itemType] || itemType
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(async () => {
  console.log('可接订单页面已挂载')
  const isApiConnected = await testApiConnection()
  if (isApiConnected) {
    getAvailableOrders()
  }
})
</script>

<style scoped>
.available-orders-container {
  padding: 20px;
}

.orders-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filter-container {
  margin: 20px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.order-list {
  margin-bottom: 20px;
}

.order-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  transition: all 0.3s;
}

.order-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.order-number {
  display: flex;
  align-items: center;
  gap: 8px;
}

.fee-amount {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
}

.order-content {
  margin-bottom: 12px;
}

.address-info {
  margin-bottom: 12px;
}

.sender-info, .receiver-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  gap: 12px;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 60px;
  font-weight: 500;
  color: #666;
}

.info-content {
  flex: 1;
}

.contact {
  font-weight: 500;
  margin-bottom: 2px;
}

.address {
  color: #666;
  font-size: 14px;
}

.item-info {
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.item-detail, .fee-detail {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 14px;
  color: #666;
}

.item-detail {
  margin-bottom: 4px;
}

.order-remark {
  display: flex;
  gap: 8px;
  font-size: 14px;
  color: #666;
  background: #fff7e6;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #faad14;
}

.remark-label {
  font-weight: 500;
  min-width: 40px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.order-time {
  font-size: 14px;
  color: #999;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.empty-placeholder {
  margin: 60px 0;
}

.loading {
  margin: 20px 0;
}

.accept-dialog-content {
  padding: 10px 0;
}

.order-summary {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.order-summary h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.order-summary p {
  margin: 6px 0;
  color: #666;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input, .filter-select {
    width: 100%;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .item-detail, .fee-detail {
    flex-direction: column;
    gap: 4px;
  }
}
</style> 